#include <streambuf>
#include <iostream>
#include"FunctionPtr.h"

using namespace std;

bool solve(FunctionPtr func, double begin, double end, double precision, double & answer) {
    double begin_value = func->value(begin);
    double end_value = func->value(end);
    if(begin_value < end_value) {
        std::swap(begin_value, end_value);
        std::swap(begin, end);
    }
    if( begin_value >= 0 && end_value <= 0 ) {
        if( begin_value <= precision ) {
            answer = begin;
            return true;
        }
        double center = (begin + end) / 2;
        bool can_solve_left = solve(func, begin, center, precision, answer);
        bool can_solve_right = solve(func, center, end, precision, answer);
        return ( can_solve_left || can_solve_right );
    }
    return false;
}

double integrate(FunctionPtr func, double begin, double end, double step) {
    bool reverce_integration = false;
    if (begin > end) {
        reverce_integration = true;
        std::swap(begin, end);
    }
    double answer = 0;
    while(begin < end) {
        answer += func->value(begin) * step;
        begin += step;
    }
    if(reverce_integration)
        return -answer;
    return answer;
}